package com.xd.core.business.controller;


import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.common.util.OrderNumUtil;
import com.xd.common.util.SecurityUtil;
import com.xd.core.business.dto.MortgageQuery;
import com.xd.core.business.entity.Contract;
import com.xd.core.business.entity.IncomingInfo;
import com.xd.core.business.entity.Mortgage;
import com.xd.core.business.entity.OutInfo;
import com.xd.core.business.mapper.ContractMapper;
import com.xd.core.business.mapper.IncomingInfoMapper;
import com.xd.core.business.mapper.OutInfoMapper;
import com.xd.core.business.service.IMortgageService;
import com.xd.core.business.vo.IncomingInfoMortgageVo1;
import com.xd.core.business.vo.MortgagePageVo;
import com.xd.core.mission.entity.MissionCenterInfo;
import com.xd.core.mission.mapper.MissionCenterInfoMapper;
import com.xd.core.product.entity.Product;
import com.xd.core.product.mapper.ProductMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 抵押表 前端控制器
 * </p>
 *
 * @author ZX
 * @since 2025-02-26
 */
@Api(tags = "抵押")
@RestController
@RequestMapping("/business/mortgage")
public class MortgageController {
    @Autowired
    private IMortgageService iMortgageService;
    @Autowired
    private IncomingInfoMapper incomingInfoMapper;
    @Autowired
    private MissionCenterInfoMapper missionCenterInfoMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OutInfoMapper outInfoMapper;

    @ApiOperation("抵押办理--借款详情")
    @GetMapping("/updateCreditAccount/{id}")
    public IncomingInfoMortgageVo1 getDetail(@PathVariable Integer id) {
        return iMortgageService.getDetail1(id);
    }


    @PreAuthorize("hasAnyAuthority('sys:MortgageOrder-viewDetails')")
    @ApiOperation("抵押订单列表")
    @PostMapping("/getMortgageList")
    public Page<MortgagePageVo> getMortgageList(@RequestBody MortgageQuery mortgageQuery) {
        return iMortgageService.getMortgageList(mortgageQuery);
    }

    @ApiOperation("导出--抵押订单列表")
    @PostMapping("/exportMortgageList")
    public void exportMortgageList(@RequestBody MortgageQuery query) {
        //插入数据状态是正在导出
        MissionCenterInfo missionCenterInfo = new MissionCenterInfo();
        missionCenterInfo.setCompanyId(SecurityUtil.getLoginCompanyId());
        missionCenterInfo.setFileStatus(SysConstant.YSZT_FILE_STATUS_ONE);
        missionCenterInfo.setCreateTime(new Date());
        missionCenterInfo.setUserId(SecurityUtil.getLoginUserId());
        missionCenterInfoMapper.insert(missionCenterInfo);

        iMortgageService.exportIncomingInfoList(query, missionCenterInfo.getId());
    }

    @PreAuthorize("hasAnyAuthority('sys:Incoming-MortgageProcess')")
    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("办理抵押")
    @PostMapping("/insertMortgage/{outId}/{incomingId}")
    public void insertMortgage(@PathVariable Integer outId,@PathVariable Integer incomingId) {
        IncomingInfo incomingInfo = incomingInfoMapper.selectById(incomingId);
        if (SysConstant.ORDER_DISABLE.equals(incomingInfo.getIsEnable())) {
            throw new XkdException("该订单已被平台停用");
        }
        Integer count = contractMapper.selectCount(new LambdaQueryWrapper<Contract>()
                .eq(Contract::getOutId, outId).in(Contract::getType, SysConstant.CONTRACT_TYPE_SIX,SysConstant.CONTRACT_TYPE_SEVEN)
                .eq(Contract::getStatus,SysConstant.CONTRACT_DO));
        if (count != 2) {
            throw new XkdException("用户有合同未签署完毕");
        }
        Mortgage mortgage = new Mortgage();
        String mortgageNo = OrderNumUtil.getMortgageNo();
        mortgage.setOrderNo(mortgageNo);
        mortgage.setIncomingId(incomingId);
        mortgage.setOutId(outId);
        Product product = productMapper.selectById(incomingInfo.getProductId());
        if (product.getType().equals(SysConstant.PRODUCT_TWO)) {
            mortgage.setMortgage("车");
        } else {
            mortgage.setMortgage("房");
        }
        iMortgageService.save(mortgage);
        outInfoMapper.updateStatus(SysConstant.BUSINESS_STATUS_EIGHT, outId);
    }


    @Transactional(rollbackFor = Exception.class)
    @ApiOperation("编辑抵押")
    @PostMapping("/updateMortgage")
    public void updateMortgage(@RequestBody Mortgage mortgage) {
        IncomingInfo incomingInfo = incomingInfoMapper.selectById(mortgage.getIncomingId());
        if (SysConstant.ORDER_DISABLE.equals(incomingInfo.getIsEnable())) {
            throw new XkdException("该订单已被平台停用");
        }
        mortgage.setUpdateBy(SecurityUtil.getLoginUserId());
        mortgage.setUpdateTime(new Date());
        iMortgageService.updateById(mortgage);
        String status;
        if ("2".equals(mortgage.getStatus())) {
            //单录：抵押完成后-->待放款
            status =  SysConstant.BUSINESS_STATUS_ELEVEN ;
            outInfoMapper.updateStatus(status, mortgage.getOutId());
        }
    }
}
